<?php

namespace App\Admin\Models;

use App\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\SoftDeletes;

class ApiDocumentCategory extends Model
{
    use SoftDeletes;

    use ModelTree {
        ModelTree::allNodesQuery as parentAllNodesQuery;
    }

    protected $guarded = []; 

    public function __construct(){
        parent::__construct();
        $this->mergeCasts(SystemModel::fieldCasts($this->getTable()));
    }
    
    public function add($data){
        $result = $this->firstOrCreate($data);
        $inputs['updated_at'] = null;
        $result->update($data);
        return $result;
    }

    public function createCategory($catalog, $parent_id=null){
        $arr['name'] = substr($catalog,0,stripos($catalog,'/'));
        $arr['parent_id'] = $parent_id ?: 0;  
        if (!$arr['name']) {
            return $arr['parent_id'];
        } else {
            $apiDocumentCategory = $this->add($arr);
            $parent_id = $apiDocumentCategory->id;
            return $this->createCategory(substr($catalog,stripos($catalog,'/')+1),$parent_id);
        }
    }
}
